//
//  BaseSearch.swift
//  ios-template
//
//  Created by lvyii000 on 2021/8/30.
//  Copyright © 2021 耳東陈. All rights reserved.
//

import SwiftUI

struct BaseSearch: View {
    
    @Binding var searchText: String
    var placeholder:String? = "请输入搜索内容"
    var onChange: ((String) -> Void)?
    var onCommit: ((String) -> Void)?

    var body: some View {
        let binding = Binding<String>(get: {
            self.searchText
        }, set: {
            self.searchText = $0
            if self.onChange != nil {
                self.onChange!(self.searchText)
            }
        })
        
       HStack {
            HStack {
                Image(systemName: "magnifyingglass")

                TextField(placeholder!, text: binding, onEditingChanged: { (isEditing) in
                    if(isEditing) {
                        
                    }
                }) {
                    if self.onCommit != nil {
                        self.onCommit!(self.searchText)
                    }
                    UIApplication.shared.windows.first { $0.isKeyWindow }?.endEditing(true)
                }
                .foregroundColor(.primary)
                .keyboardType(.default)
                .onTapGesture {}
                .onLongPressGesture(pressing: { (isPressed) in
                    if isPressed {
                        self.endEditing()
                    }
                }) {
                    //perform
                }

                Button(action: {
                    self.searchText = ""
                    if self.onCommit != nil {
                        self.onCommit!(self.searchText)
                    }
                }) {
                    Image(systemName: "xmark.circle.fill")
                        .opacity(searchText == "" ? Double(0) : Double(0.6))
                }

            }
            .padding(EdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12))
            .foregroundColor(.secondary)
            .background(Color(.tertiarySystemFill))
            .cornerRadius(30.0)
       }
    }
}

extension View {
   fileprivate func endEditing() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

struct BaseSearch_Previews: PreviewProvider {
    static var previews: some View {
        BaseSearch(searchText: .constant(""))
    }
}
